package cn.itcast.sailing.job;

import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.scheduling.quartz.SpringBeanJobFactory;

import javax.annotation.PostConstruct;
@Configuration
public class SchedulerConfig {

    @Autowired
    private MusicJob musicJob;
    @Bean
    public SchedulerFactoryBean schedulerFactoryBean(ApplicationContext applicationContext) {
        SchedulerFactoryBean factory = new SchedulerFactoryBean();
        // 其他配置...

        // 设置ApplicationContext
        factory.setApplicationContext(applicationContext);

        // 如果使用SpringBeanJobFactory
        factory.setJobFactory(new SpringBeanJobFactory());
        // ...其他配置
        factory.setTriggers(cronTrigger());

        // 添加以下代码以注册作业到调度器
        factory.setJobDetails(musicJobDetail()); // 将作业详情注册到调度器工厂
        return factory;
    }


    @Bean
    public CronTrigger cronTrigger() {
        CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule("   0 13 * * *"); // 每12小时执行一次的cron表达式
        return TriggerBuilder.newTrigger().forJob(musicJobDetail()).withIdentity("cronTrigger").withSchedule(scheduleBuilder).build();
    }

    @Bean
    public JobDetail musicJobDetail() {
        return JobBuilder.newJob(MusicJob.class)
                .withIdentity("musicJob", "group1")
                .storeDurably(true)
                .build();
    }
}
